package com.das.mechanic_base.service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;

import androidx.annotation.Nullable;

import com.das.mechanic_base.bean.common.AwsFileBean;
import com.das.mechanic_base.bean.common.GenerateLiveBean;
import com.das.mechanic_base.bean.live.VideoInfoBean;
import com.das.mechanic_base.mapi.api.NetWorkHttp;
import com.das.mechanic_base.mapi.response.HttpCallBack;
import com.das.mechanic_base.mapi.schedulers.RxSchedulersHelper;
import com.das.mechanic_base.utils.X3FileRequestBody;
import com.das.mechanic_base.utils.X3NetUtils;
import com.das.mechanic_base.utils.SpHelper;
import com.hjq.toast.ToastUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import io.reactivex.disposables.Disposable;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class UploadVideoService extends Service {
    public  boolean isGoon = true;//false  记录取消时 进度不在展示
    private String path;
    private long allSize;
    private Context context;
    public static Disposable disposable;
    public  Disposable disVideo;
    private  boolean isInfo;//记录只发一次消息
    private long workBaseId;
    private Myreceiver receiver;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        isInfo = true;
        context =this;

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        receiver = new Myreceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("UploadVideoServiceBroadcast");
        registerReceiver(receiver, filter);
        if (intent != null && intent.getStringExtra("path") != null  ) {
            long carId = intent.getLongExtra("carId", 0L);
            workBaseId = intent.getLongExtra("workBaseId", 0L);
            path = intent.getStringExtra("path");
            File imgFile = new File(path);

            RequestBody requestFile = RequestBody.create(MediaType.parse("video/*"), imgFile);
            X3FileRequestBody fileRequestBody = new X3FileRequestBody(requestFile, (currentLength, contentLength) -> {

                if(isGoon) {
                    allSize = contentLength;
//                    videoInfoBean.contentLength = contentLength;
//                    videoInfoBean.currentLength = currentLength;
//                    videoInfoBean.path = path;
//                    videoInfoBean.workBaseId = workBaseId;
                    VideoInfoBean videoInfoBean = new VideoInfoBean(currentLength,contentLength,path,workBaseId,0,0);
                    Intent intent1 = new Intent();
                    intent1.putExtra("complete", false);
                    intent1.putExtra("VideoInfoBean", videoInfoBean);
                    intent1.setAction(UploadVideoService.class.getName());
                    sendBroadcast(intent1);
                    if (videoInfoBean.contentLength == videoInfoBean.currentLength) {
                        SpHelper.saveData("videoInfoBean",videoInfoBean.toString());
                        return;
                    }
                    if (X3NetUtils.getNetWorkType(context) == 0) {
                        videoInfoBean.status = 1;
                        EventBus.getDefault().post("iscancelshowred");
                        SpHelper.saveData("videoInfoBean",videoInfoBean.toString());
                        return;
                    }
                    if (isInfo) {//只发一次
                        EventBus.getDefault().post("isshowred");
                        SpHelper.saveData("workBaseId" + workBaseId, workBaseId);
                        isInfo = false;
                    }


                }
            });
            try {
                String  filename = URLEncoder.encode(imgFile.getName(), "UTF-8");
                MultipartBody.Part fileBody = MultipartBody.Part.createFormData("multipartFile", filename, fileRequestBody);
                Map<String, RequestBody> map = new HashMap<>();
                map.put("description", fileRequestBody.create(MediaType.parse("multipart/form-data"), "视频"));
//            map.put("ossBucketName", fileRequestBody.create(MediaType.parse("multipart/form-data"), "SERVICE_PIC"));

                NetWorkHttp.getApi().uploadVideo(map, fileBody).compose(RxSchedulersHelper.defaultComposeRequest())
                        .subscribe(new HttpCallBack<AwsFileBean>() {
                            @Override
                            protected void onDone(AwsFileBean awsFileBean) {
                                System.out.println("上传成功" + "  ");
                                if (awsFileBean != null){
                                    getLiveInfoByUploadVideo(carId, true, awsFileBean.id, workBaseId);
                                } else {
                                    ToastUtils.show("upload fail");
                                }
                            }

                            @Override
                            protected String LoadingMessage() {
                                return null;
                            }

                            @Override
                            protected void onCancelNet(Disposable disposable) {
                                super.onCancelNet(disposable);
                                UploadVideoService.this.disposable = disposable;
                            }

                            @Override
                            protected void showError(String error) {
                                SpHelper.saveData("videoInfoBean","");
                                SpHelper.saveData("workBaseId"+ workBaseId,0);
                                EventBus.getDefault().post("iscancelshowred");
                            }
                        });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return super.onStartCommand(intent, flags, startId);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();

    }

    public void getLiveInfoByUploadVideo(long carId, boolean isCarOwnerRequired, long resourceId, long workBaseId) {
        NetWorkHttp.getApi().generateLiveInfoByUploadVideo(carId, isCarOwnerRequired, resourceId, workBaseId)
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .subscribe(new HttpCallBack<GenerateLiveBean>() {
                    @Override
                    protected void onDone(GenerateLiveBean generateLiveBean) {
                        System.out.println("上传成功了" + "  ");
//                        videoInfoBean.contentLength = allSize;
//                        videoInfoBean.currentLength = allSize;
//                        videoInfoBean.path = path;
//                        videoInfoBean.workBaseId = workBaseId;
//                        videoInfoBean.uploadVideoResourceId = generateLiveBean.uploadVideoResourceId;
                        VideoInfoBean videoInfoBean = new VideoInfoBean(allSize,allSize,path,workBaseId,generateLiveBean.uploadVideoResourceId,0);
                        Intent intent1 = new Intent();
                        intent1.putExtra("VideoInfoBean", videoInfoBean);
                        intent1.putExtra("complete",true);
                        intent1.setAction(UploadVideoService.class.getName());
                        sendBroadcast(intent1);
                        SpHelper.saveData("videoInfoBean","");
                        SpHelper.saveData("videoInfoBean",videoInfoBean.toString());
                        SpHelper.saveData("workBaseId"+workBaseId,workBaseId);
                        EventBus.getDefault().post("iscancelshowred");
                        if ( receiver!= null) {
                            try {
                                unregisterReceiver(receiver);
                            } catch (IllegalArgumentException e) {
                            }
                        }
                        stopSelf();
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }
                    @Override
                    protected void onCancelNet(Disposable disposable) {
                        super.onCancelNet(disposable);
                        UploadVideoService.this.disVideo = disposable;
                    }
                    @Override
                    protected void showError(String error) {
                        SpHelper.saveData("videoInfoBean","");
                        SpHelper.saveData("workBaseId"+workBaseId,0);
                        EventBus.getDefault().post("iscancelshowred");
                    }
                });
    }
    private class Myreceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            if(disposable != null){
                disposable.dispose();
                EventBus.getDefault().post("iscancelshowred");
                System.out.println("删除了");
                isGoon = false;
                SpHelper.saveData("workBaseId"+workBaseId,0);
                if ( receiver!= null) {
                    try {
                        unregisterReceiver(receiver);
                    } catch (IllegalArgumentException e) {
                    }
                }
                stopSelf();

            }
            if(disVideo != null){
                disVideo.dispose();
                EventBus.getDefault().post("iscancelshowred");
                System.out.println("删除了");
                SpHelper.saveData("workBaseId"+workBaseId,0);
                isGoon = false;
                if ( receiver!= null) {
                    try {
                        unregisterReceiver(receiver);
                    } catch (IllegalArgumentException e) {
                    }
                }
                stopSelf();
            }
        }
    }
}
